<?php


namespace App\Http\Controllers;


use App\Handlers\OtherHandler;
use App\Http\Handlers\MailHandler;
use App\Http\Requests\AuthRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\View;


class AuthController extends MainController {

    protected $model = User::class;

    protected function registration( AuthRequest $request ) {
        $request->validated();
        if($model=$this->save( $request )) {
            $this->checkLogin();
            $token=$model->createToken('activate_token');
            try {
                (new MailHandler(asset('register/confirmation?token='.$token),
                    'mails.mail',
                    $model->toArray()))->sendMail($model->email,'Confirm email');
            } catch (\Exception $e) {
                Log::info($e->getMessage());
            }
            return redirect('/register/confirm');
        }
        return redirect('/404');
    }

    protected function login( AuthRequest $request ) {
        if(User::where('email',$request->input('email'))->first()==null){
            return $this->registration($request);
        }
        if($this->checkLogin()){
            return redirect('/');
        }
        return view( 'pages/authorization/login', [
            "error"          => 'E-mail или пароль не совпадают. Пожалуйста, попробуйте еще раз.',
            "type_meta_info" => 'login'
        ] );

    }

    private function checkLogin() {
        global $request;
        $credentials = array_merge($request->only( 'email', 'password' ),['active'=>1]);
        if ( Auth::attempt( $credentials ) ) {
            return OtherHandler::urlBack();
        }
        return false;
    }
    public function confirmation( Request $request ) {
        $token=$request->input('token');
        $user=$this->model::where('activate_token',$token)->first();
        if($user) {
            $user->activate();
            Auth::login($user);
            return view('pages/authorization/confirmation_email', [
                "confirm" => true,
                "message" => 'Email успешно активирован.',
                "type_meta_info" => "register"
            ]);
        }
        return view('pages/authorization/confirmation_email', [
            "confirm" => false,
            "message" => 'Email не зарегистрирован.',
            "type_meta_info" => "register"
        ]);
    }
    public function logout( Request $request ) {

        Auth::logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect( '/' );
    }


}
